<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="searchForm" :inline="true" :model="searchForm" :size="size">
        <el-form-item prop="keyword" label="应用Id/名称：">
          <el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable>
            <el-button slot="append" :size="size" icon="el-icon-search" @click="getAppList" />
          </el-input>
        </el-form-item>
      </el-form>
      <el-button v-has="'btn_add'" class="filter-item" type="primary" icon="el-icon-plus" :size="size"
                 @click="openApplicationDialog">添加应用</el-button>
    </div>

    <el-table style="width: 100%;" :data="tableList" fit border highlight-current-row :size="size">
      <el-table-column prop="clientId" label="应用Id" align="center" min-width="150" />
      <el-table-column prop="clientName" label="应用名称" align="center" min-width="130" />
      <el-table-column prop="description" label="描述说明" align="center" min-width="130" />
      <el-table-column prop="adminNames" label="应用管理员" align="center" min-width="130" />
      <el-table-column prop="status" label="状态" align="center" min-width="80">
        <template slot-scope="{row}">
          <el-tag size="small" :type="statusArr[row.status].type">{{ statusArr[row.status].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createUsername" label="创建人" align="center" min-width="80" />
      <el-table-column prop="createTime" label="创建时间" align="center" min-width="130" />
      <el-table-column label="操作" fixed="right" align="center" min-width="100">
        <template slot-scope="{row}">
          <el-button v-has="'btn_edit'" type="text" :size="size" @click="editApp(row)">
            编辑
          </el-button>
          <el-button v-has="'btn_delete'" type="text" :size="size" @click="deleteApp(row)" style="color: #e6a23c">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="searchForm.page" :limit.sync="searchForm.limit"
                @pagination="getAppList" />

    <!-- 新增编辑弹框 -->
    <el-dialog class="app-dialog" :title="dialogEdit ? '编辑' : '新增'" :visible.sync="dialogAddShow"
               :modal="true" :close-on-click-modal="closeOnclickModal" @close="closeDialog">
      <el-form ref="dialogAddForm" :model="dialogAddForm" :size="size" label-width="150px">
        <el-form-item label="应用ID：" :rules="rf_rules({required:true})" prop="clientId">
          <el-input v-model="dialogAddForm.clientId" disabled />
        </el-form-item>
        <el-form-item label="应用名称：" :rules="rf_rules({required:true})" prop="clientName">
          <el-input v-model="dialogAddForm.clientName" placeholder="请输入应用名称" clearable />
        </el-form-item>
        <el-form-item label="应用描述：" prop="description">
          <el-input type="textarea" :rows="4" v-model="dialogAddForm.description"
                    placeholder="请输入应用描述" clearable />
        </el-form-item>
        <el-form-item label="应用管理员：" :rules="rf_rules({required:true})">
          <el-tag class="margin-right-10" v-for="(tag, index) in dialogAddForm.adminInfoDtoList" :key="tag.id" closable
                  :size="size" @close="deleteAdmin(index)">
            {{tag.username}}
          </el-tag>
          <el-button type="primary" :size="size" @click="addAdmin">添加</el-button>
        </el-form-item>
        <el-form-item label="状态" :rules="rf_rules({required:true})" prop="status">
          <el-radio-group v-model="dialogAddForm.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否同步人员数据：" :rules="rf_rules({required:true})"
                      prop="sysClientConfig.dataSync">
          <el-radio-group v-model="dialogAddForm.sysClientConfig.dataSync" :disabled="dialogEdit">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item :label="$t('FORM.CONFIGURED_PARAMETERS')"></el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="closeDialog">取消</el-button>
        <el-button type="primary" :size="size" @click="saveApp">确定</el-button>
      </span>
    </el-dialog>

    <!-- 添加应用管理员 -->
    <el-dialog class="app-dialog" title="添加应用管理员" :visible.sync="dialogAdminShow"
               :modal="true" :close-on-click-modal="closeOnclickModal" @close="closeAdminDialog">
      <el-form ref="dialogAdminForm" :model="dialogAdminForm" :size="size" label-width="120px">
        <el-form-item label="管理员手机号" :rules="rf_rules({required:true, type: 'phone'})" prop="phone">
          <el-input v-model="dialogAdminForm.phone" placeholder="请输入管理员手机号"
                    :disabled="!isFirstStep" clearable />
        </el-form-item>
        <el-form-item v-if="!isFirstStep" label="管理员姓名" :rules="rf_rules({required:true})"
                      prop="username">
          <el-input v-model="dialogAdminForm.username" placeholder="请输入管理员姓名" :disabled="hasUser"
                    clearable />
        </el-form-item>
        <div v-show="!isFirstStep" class="tip">
          <span class="el-icon-info tip-icon"></span>
          <span>{{ hasUser ? '平台已经存在此用户' : '平台不存在此用户，请输入管理员姓名后确认添加' }}</span>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="cancelAdmin">
          {{ isFirstStep ? '取消' : '上一步' }}</el-button>
        <el-button type="primary" :size="size" @click="saveAdmin">
          {{ isFirstStep ? '搜索' : '确定' }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from "@/components/Pagination"
  import {mapGetters} from "vuex"
  import api from '@/utils/api.js'
  import util from '@/utils/util.js'
  export default {
    name: 'app',
    components: {
      Pagination
    },
    data () {
      return {
        searchForm: {
          keyword: '',
          limit: 10,
          page: 0,
          stat: true
        },
        dialogAddForm: {
          id: '',
          clientId: '',
          description: '',
          status: 1,
          clientName: '',
          adminInfoDtoList: [],
          sysClientConfig: {
            dataSync: true
          }
        },
        dialogAdminForm: {
          id: '',
          username: '',
          phone: ''
        },
        dialogAddShow: false,
        dialogAdminShow: false,
        dialogEdit: false,
        tableList: [],
        total: 0,
        isFirstStep: true,
        hasUser: false,
        statusArr: [{
          label: '禁用',
          type: 'danger'
        }, {
          label: '启用',
          type: ''
        }]
      }
    },
    computed: {
      ...mapGetters(['size', 'closeOnclickModal'])
    },
    mounted () {
      this.getAppList()
    },
    methods: {
      // 初始化列表
      getAppList () {
        const params = Object.assign({}, this.searchForm)
        api.getAllAppList(params).then(response => {
          this.tableList = response.data.list
          this.total = response.data.count
        })
      },
      // 打开添加应用的模态框
      openApplicationDialog () {
        this.dialogAddShow = true
        this.dialogEdit = false
        api.genAppId().then(res => {
          this.dialogAddForm.clientId = res.data
        })
      },
      // 编辑
      editApp (row) {
        this.dialogEdit = true
        this.dialogAddShow = true
        api.getAppDetail({id: row.id}).then(res => {
          this.dialogAddForm = util.assignSame(this.dialogAddForm, res.data)
          this.dialogAddForm.adminInfoDtoList = res.data.adminList.map(item => {
            item.username = item.realName
            return item
          })
        })
      },
      // 删除
      deleteApp (row) {
        const id = row.id
        this.delConfirm().then(() => {
          api.deleteApp({id}).then(response => {
            this.getAppList()
          })
        })
      },
      // 添加成员
      addAdmin () {
        this.dialogAdminShow = true
      },
      // 保存应用
      saveApp () {
        this.validateSubmit('dialogAddForm').then(() => {
          const params = this.dialogAddForm
          api.saveOrUpdateApp(params).then(res => {
            this.$message.success('操作成功')
            this.closeDialog()
            this.getAppList()
          })
        }).catch(() => {})
      },
      // 添加应用管理员
      saveAdmin () {
        this.validateSubmit('dialogAdminForm').then(() => {
          if (this.isFirstStep) {
            const params = {
              phone: this.dialogAdminForm.phone,
              clientId: this.dialogAddForm.clientId
            }
            api.findUserByPhone(params).then(res => {
              this.isFirstStep = false
              if (res.data) {
                this.hasUser = true
                this.dialogAdminForm.username = res.data.realName
                this.dialogAdminForm.id = res.data.id
              } else {
                this.dialogAdminForm.username = ''
                this.hasUser = false
              }
            })
          } else {
            if (!this.dialogAdminForm.id) delete this.dialogAdminForm.id
            const temp = Object.assign({}, this.dialogAdminForm)
            const idArr = this.dialogAddForm.adminInfoDtoList.filter(item => {
              return item.id !== undefined
            }).map(item => item.id)
            const phoneArr = this.dialogAddForm.adminInfoDtoList.filter(item => {
              return item.phone !== undefined
            }).map(item => item.phone)
            if (idArr.includes(temp.id) || phoneArr.includes(temp.phone)) {
              this.$message.warning('你已添加过此用户')
            } else {
              this.dialogAddForm.adminInfoDtoList.push(temp)
              this.closeAdminDialog()
            }
          }
        })
      },
      // 删除应用管理员
      deleteAdmin (index) {
        this.dialogAddForm.adminInfoDtoList.splice(index, 1)
      },
      // 应用管理员弹框取消
      cancelAdmin () {
        if (this.isFirstStep) {
          this.closeAdminDialog()
        } else {
          this.isFirstStep = true
          this.dialogAdminForm.username = ''
        }
      },
      // 关闭用户弹框
      closeAdminDialog () {
        this.$refs['dialogAdminForm'].resetFields()
        this.dialogAdminShow = false
        this.isFirstStep = true
        this.hasUser = false
        this.dialogAdminForm.id = ''
      },
      // 关闭新增弹框
      closeDialog () {
        this.$refs['dialogAddForm'].resetFields()
        this.dialogAddShow = false
        this.dialogAddForm.adminInfoDtoList = []
        this.dialogAddForm.id = ''
      }
    }
  }
</script>

<style lang="scss">
  .app-container {
    .app-dialog {
      .el-dialog {
        width: 30%;
        min-width: 500px;
      }

      .tip {
        width: 80%;
        text-align: center;
        background: rgb(230, 247, 255);
        border: 1px solid rgb(145, 213, 255);
        border-radius: 4px;
        padding: 5px 0;
        margin-left: 50px;

        &-icon {
          color: rgb(24, 144, 255);
          margin-right: 2px;
        }
      }
    }
  }
</style>
